package com.mjkj.util;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;


public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    private static boolean license = false;

    /**
     * 保存多个图片的路径
     *
     * @param files   文件列表
     * @param dirPath 存储目录
     * @return 文件路径的URL列表
     */
    public static List<String> saveFiles(List<MultipartFile> files, String dirPath) {
        File path = null;
        List<String> urlList = new ArrayList<>();
        try {
            int i = 1;
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    //获取后缀名
                    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).trim().toLowerCase();
                    //设置允许上传文件类型
                    String suffixList = "jpg,png,ico,bmp,jpeg,zip,pdf,bin,rar,7z,zip,xyz,apk";
                    //判断是否包含
                    if (suffixList.contains(suffix)) {
                        suffix = "." + suffix;
                        //查看路径是否存在，不存在就创建
                        path = new File(ResourceUtils.getURL("classpath:").getPath());
                        if (!path.exists()) {
                            path = new File("");
                        }
                        File upload = new File(path.getAbsolutePath(), dirPath);
                        if (!upload.exists()) {
                            upload.mkdirs();
                        }
                        String ID = getIdInMillis() + (i++);
                        String realFilePath = upload.getAbsolutePath() + "/" + ID + suffix;
                        String url = dirPath + "/" + ID + suffix;
                        //spring的transferTo保存文件方法
                        file.transferTo(new File(realFilePath));
                        urlList.add(url);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            new FileNotFoundException(e.getMessage() + "The file directory does not exist!");
            return null;
        } catch (IOException e) {
            new IOException(e.getMessage() + "File saving error");
        }
        return urlList;
    }

    /**
     * 保存文件的路径
     *
     * @param file    文件列表
     * @param dirPath 存储目录
     * @return 文件路径的URL列表
     */
    public static String saveFile(MultipartFile file, String dirPath) {
        File path = null;
        try {
            if (!file.isEmpty()) {
                //获取后缀名
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).trim().toLowerCase();

                //查看路径是否存在，不存在就创建
                //image/jpeg
                path = new File(ResourceUtils.getURL("classpath:").getPath());
                if (!path.exists()) {
                    path = new File("");
                }
                File upload = new File(path.getAbsolutePath(), dirPath);
                if (!upload.exists()) {
                    upload.mkdirs();
                }
                String ID = getIdInMillis();
                String realFilePath = upload.getAbsolutePath() + "/" + ID + suffix;
                String url = dirPath + "/" + ID + suffix;
                File saveFile = new File(realFilePath);
                file.transferTo(saveFile);
                return url;
            }
        } catch (FileNotFoundException e) {
            new FileNotFoundException(e.getMessage() + "文件夹不存在");
            return null;
        } catch (IOException e) {
            new IOException(e.getMessage() + "文件保存错误");
        }
        return null;
    }

    public static String getIdInMillis() {
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        return String.valueOf(timeInMillis);
    }

    /**
     * 根据excel模板生成文件
     * @param templateFilePath 模板文件路径
     * @param filePath         生成的文件路径
     * @param excelData        excel的固定数据
     * @param mapList          动态表格数据
     * @param type             文件类型
     * @return                 文件路径
     * @throws Exception       异常
     */
    public static String fileGenerateByExcelTemplate(String templateFilePath, String filePath, Map<String,Object> excelData, List<Object> mapList,String type) throws Exception {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path.exists()){
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(), "");
        if(!upload.exists()){
            upload.mkdirs();
        }
        ClassPathResource classPathResource = new ClassPathResource(templateFilePath);
        String saveFilePath = upload.getPath() + filePath;

        int size = mapList.size();

        switch(type) {
            case ".xlsx" :
                ExcelWriter excelWriter = EasyExcel.write(saveFilePath + type).withTemplate(classPathResource.getPath()).build();
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build();
                excelWriter.fill(mapList, fillConfig, writeSheet);
                excelWriter.fill(excelData, writeSheet);
                excelWriter.finish();
                return filePath + type;
            default:
                return filePath + type;
        }
    }

    /**
     * 删除文件
     * @param filePath
     */
    public static boolean removeFileById(String filePath) {
        File file = new File("C:/safety-production-management" + filePath);
        // 路径为文件且不为空则进行删除
        boolean flag = false;
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

}
